import pygame
from pygame.sprite import Sprite
import random
from bullet import EnemyBullet
class Alien(Sprite):
    """表示列队外星人的类"""
    def __init__(self, ai_settings, screen, x, y):
        """初始化外星人并设置其起始位置"""
        super().__init__()
        self.screen = screen
        self.ai_settings = ai_settings
        self.rect = pygame.Rect(x, y, 50, 50)

        self.rect.x = x
        self.rect.y = y
        self.x = float(x)
        self.y = float(y)

        # 为外星人添加生命值
        self.max_hp = 1     # 默认1点生命值
        self.current_hp = self.max_hp   # 当前生命值

        # 发射控制
        self.can_shoot = True    # 是否可以发射
        self.shoot_cooldown = 2000      # 发射冷却（毫秒）
        self.last_shot_time = 0     # 上次发射时间

    def try_shoot(self, current_time, target=None):
        """尝试发射子弹（返回子弹对象或None）"""
        self.last_shot_time = current_time
        self.can_shoot = False      # 进入冷却
        return EnemyBullet(
            self.ai_settings,
            self.screen,
            self.rect.centerx,
            self.rect.bottom,
            target.rect.centerx,    # 飞船x
            target.rect.centery     # 飞船y
        )

    def update(self):
        """更新设计冷却状态"""
        current_time = pygame.time.get_ticks()
        if not self.can_shoot and current_time - self.last_shot_time >= self.shoot_cooldown:
            self.can_shoot = True       # 重置发射状态

    def take_damage(self, amount):
        """接受伤害，返回是否被摧毁"""
        self.current_hp -= amount

        if self.current_hp <= 0:

            return True
        return False

    def on_destroy(self):
        """外星人毁灭"""
        self.kill()     # 从精灵组移除


class Lined_Alien(Alien):
    """列队外星人"""
    def __init__(self, ai_settings, screen, x, y, column, row):
        super().__init__(ai_settings, screen, x, y)
        # 加载外星人图像，并设置其rect属性
        self.image = pygame.image.load("D:/game_program/Alien_Invasion/敌军1级.png")
        self.rect = self.image.get_rect()

        # 进场动画参数
        self.entering = True    # 是否正在进场
        self.enter_speed = 2    # 进场速度
        self.target_y = y       # 目标Y坐标
        self.rect.y = -self.rect.height     # 初始位置在屏幕上方外

        # 队列位置信息
        self.column = column
        self.row = row

        # 移动参数
        self.direction = 0.5      # 1=右，-1=左
        self.line_speed_factor = 1   # 列队外星人移动速度
        self.drop_speed = ai_settings.fleet_drop_speed

        # 血量
        self.max_hp = 1
        self.current_hp = self.max_hp

    def update(self):
        """更新外星人位置"""
        if self.entering:
            # 垂直下落进场
            self.rect.y += self.enter_speed
            if self.rect.y >= self.target_y:
                self.entering = False
        else:
            # 常规水平移动
            self.x += self.line_speed_factor * self.direction
            self.rect.x = self.x

        # 边缘检测
        if self.check_edges():
            self.y += self.ai_settings.fleet_drop_speed
            self.rect.y = self.y
            self.direction *= -1

    def check_edges(self):
        """检测是否触碰屏幕边缘"""
        screen_rect = self.screen.get_rect()
        return (self.rect.right > screen_rect.right) or (self.rect.left < 0)

    def try_shoot(self, current_time, target=None):
        """尝试发射子弹（返回子弹对象或None）"""
        # 只有不在进场动画且冷却结束才能发射
        if (not getattr(self, 'entering', False) and
                self.can_shoot and
                current_time - self.last_shot_time >= self.shoot_cooldown):

            self.last_shot_time = current_time

            if target:  # 瞄准模式
                return EnemyBullet(
                    self.ai_settings,
                    self.screen,
                    self.rect.centerx,
                    self.rect.bottom,
                    target.rect.centerx,
                    target.rect.centery
                )
            else:  # 直线向下
                return EnemyBullet(
                    self.ai_settings,
                    self.screen,
                    self.rect.centerx,
                    self.rect.bottom
                )
        return None




def create_fleet_with_entrance(ai_settings, screen, aliens):
    """创建从屏幕外飞入的外星人舰队"""
    alien = Lined_Alien(ai_settings, screen, 0, 0, 0, 0)
    alien_width = alien.rect.width
    alien_height = alien.rect.height
    # 计算舰队布局
    available_space_x = ai_settings.screen_width - 2 * alien_width
    number_aliens_x = int(available_space_x / (2 * alien_width))
    # 修改点1：计算可用垂直空间（使用整个屏幕高度）
    available_space_y = ai_settings.screen_height - alien_height  # 留出底部空间
    vertical_spacing = alien_height * 1.5  # 行间距
    number_rows = min(5, int(available_space_y / vertical_spacing))  # 最多5排
    # 清空现有外星人
    aliens.empty()

    # 从屏幕顶部外生成
    for row in range(number_rows):
        for column in range(number_aliens_x):
            x = alien_width + 2 * alien_width * column
            y = -alien_height * (number_rows - row)  # 初始在屏幕外
            # 每个外星人延迟出现（按列延迟）
            delay_frames = column * 5
            aliens.add(
                DelayedAlien(
                    ai_settings, screen, x, y,
                    column, row, delay_frames
                 )
            )


class DelayedAlien(Lined_Alien):
    """带延迟入场的外星人"""

    def __init__(self, ai_settings, screen, x, y, column, row, delay_frames, init_y):
        super().__init__(ai_settings, screen, x, y, column, row)
        self.delay_frames = delay_frames
        self.wait_counter = 0
        self.active = False

        # 设置初始位置（屏幕外）
        self.rect.y = init_y
        self.target_y = y  # 存储目标位置
        self.entering = False  # 初始状态

    def update(self):
        if not self.active:
            self.wait_counter += 1
            if self.wait_counter >= self.delay_frames:
                self.active = True
                self.entering = True  # 激活入场状态
        else:
            if self.entering:
                # 执行入场动画
                self.rect.y += self.enter_speed
                if self.rect.y >= self.target_y:
                    self.entering = False
            else:
                # 正常舰队移动
                super().update()

class IndependentAlien(Alien):
    """独立移动的外星人（基础基础类）"""
    def __init__(self, ai_settings, screen):
        super().__init__(ai_settings, screen, 0, 0)

        # 加载图像并外接矩形
        self.image = pygame.image.load("D:/game_program/Alien_Invasion/敌军1级.png")
        self.image.get_rect()

        # 随机初始位置
        self.rect.x = random.randint(0, ai_settings.screen_width - 50)
        self.rect.y = random.randint(50, ai_settings.screen_height // 2)
        self.x = float(self.rect.x)     # 同步浮点位置
        self.y = float(self.rect.y)

        # 确保射击属性正确
        self.can_shoot = True   # 明确重置
        self.shoot_cooldown = 1500  # 明确冷却时间
        self.last_shot_time = 0  # 上次发射时间

        # 独立移动属性
        self.independent_aliens_speed = 0.3           # 移动速度
        self.direction = random.choice([1, -1])     # 随机初始移动方向
        self.speed = random.uniform(0.5, 1.5) * self.independent_aliens_speed   # 随机速度
        # 为外星人添加生命值
        self.max_hp = 2  # 默认1点生命值
        self.current_hp = self.max_hp  # 当前生命值

    def update_movement(self):
        """独立移动逻辑"""
        self.x += self.speed * self.direction   # 速度 * 方向
        # 垂直随机波动
        self.y += random.uniform(-0.5, 0.5)

        # 更新rect位置
        self.rect.x = self.x
        self.rect.y = self.y

        # 碰到边缘则反弹
        if self.check_edges():
            self.direction *= -1
            self.y += self.ai_settings.fleet_ind_drop_speed
            self.rect.y = self.y

    def check_edges(self):  # 检测是否碰撞屏幕边缘
        """如果外星人位于屏幕边缘，就返回True"""
        screen_rect = self.screen.get_rect()
        if self.rect.right > screen_rect.right:
            return True
        elif self.rect.left <= 0:
            return True
        return False

    def blitme(self):
        """在指定位置绘制外星人"""
        self.screen.blit(self.image, self.rect)

    def update(self):
        super().update()  # 调用父类的冷却检查
        self.update_movement()


